<!--
 * @Descripttion: 
 * @version: 
 * @Author: chenWeiLong
 * @Date: 2022-03-01 19:20:44
 * @LastEditors: please set LastEditors
 * @LastEditTime: 2022-03-12 15:23:09
-->
<template>
  <h1>Pinia</h1>
  <p>vue中新一代的状态管理工具</p>
  <br />
  <h3>直接修改值</h3>
  <p>{{ useStoreState.num }} ----- {{ useStoreState.msg }}</p>
  <button @click="change1">change1</button>
  <h3>$patch({})</h3>
  <p>{{ useStoreState.num }} ----- {{ useStoreState.msg }}</p>
  <button @click="change2">change2</button>
  <h3>$patch((state)=>{})</h3>
  <p>{{ useStoreState.num }} ----- {{ useStoreState.msg }}</p>
  <button @click="change3">change3</button>
  <h3>$state = {} 使用这种方式会直接覆盖式修改</h3>
  <p>{{ useStoreState.num }} ----- {{ useStoreState.msg }}</p>
  <button @click="change4">change4</button>
  <h3>调用action修改</h3>
  <p>{{ useStoreState.num }} ----- {{ useStoreState.msg }}</p>
  <button @click="change5">change5</button>

  <hr />
  <p>{{ num }}-----{{ msg }}</p>

  <button @click="reset">重置</button>

  <hr />
  <p>购物车示例</p>
  <List></List>
  <Cart></Cart>
</template>
<script lang="ts" setup>
import List from "./list.vue";
import Cart from "./cart.vue";
import { useStore } from "@/store/index";
import { storeToRefs } from "pinia";

const useStoreState = useStore();

// 直接解构pinia不具有响应式
// 解构响应式变量
const { num, msg } = storeToRefs(useStoreState);

// pinia 五中修改数据方式
const change1 = () => {
  useStoreState.num++;
};
const change2 = () => {
  useStoreState.$patch({
    num: 66,
    // msg: '通过$patch({}) 传入对象修改'
  });
};
const change3 = () => {
  useStoreState.$patch((state: any) => {
    // console.log(state)
    // state.num = 999
    state.msg = "state 代表当前引入的pinia的state";
  });
};
const change4 = () => {
  useStoreState.$state = {
    num: 123,
    msg: "mmmmmmmmmmmmmmmmmmmm",
  };
};
const change5 = () => {
  useStoreState.setNumber(555);
};

// pinia实例api

// $reset()重置pinia实例 回复原始状态
const reset = () => {
  useStoreState.$reset();
};

// 订阅state的改变
// 观察state的变化时触发
useStoreState.$subscribe((args: any, state: any) => {
  // console.log(args, state)
});

// 监听action
useStoreState.$onAction((args: any) => {
  // console.log(args);
  args.after(() => {
    // console.log('state改变之后的回调')
  });
});
</script>
<style lang="less" scoped></style>
